package asia.yuanding.wechat.web.netty.handler.impl;

import asia.yuanding.wechat.web.netty.handler.annotation.MessageProcessor;
import asia.yuanding.wechat.web.netty.handler.annotation.NettyMessageHandler;
import cn.hutool.json.JSONObject;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;

/**
 * 系统相关消息处理器
 * 
 * @author Kiro
 */
@Slf4j
@NettyMessageHandler("system")
public class SystemMessageHandler {

    @MessageProcessor(value = "ping", priority = 0)
    public String handlePing(JSONObject reqEntity, ChannelHandlerContext ctx) {
        log.debug("收到心跳消息");
        
        JSONObject response = new JSONObject();
        response.set("type", "system");
        response.set("method", "pong");
        response.set("timestamp", System.currentTimeMillis());
        
        return response.toString();
    }

    @MessageProcessor("info")
    public String getSystemInfo(JSONObject reqEntity, ChannelHandlerContext ctx) {
        String userId = getUserId(ctx);
        
        log.info("用户 {} 请求系统信息", userId);
        
        JSONObject response = new JSONObject();
        response.set("type", "system");
        response.set("method", "info");
        response.set("version", "1.0.0");
        response.set("serverTime", System.currentTimeMillis());
        response.set("onlineUsers", 100);
        
        return response.toString();
    }

    @MessageProcessor("notification")
    public String sendNotification(JSONObject reqEntity, ChannelHandlerContext ctx) {
        String message = reqEntity.getStr("message");
        String level = reqEntity.getStr("level", "info");
        String userId = getUserId(ctx);
        
        log.info("向用户 {} 发送通知: {} (级别: {})", userId, message, level);
        
        JSONObject response = new JSONObject();
        response.set("type", "system");
        response.set("method", "notification");
        response.set("message", message);
        response.set("level", level);
        response.set("timestamp", System.currentTimeMillis());
        
        return response.toString();
    }

    private String getUserId(ChannelHandlerContext ctx) {
        Object userId = ctx.channel().attr(AttributeKey.valueOf("uId")).get();
        return userId != null ? userId.toString() : "unknown";
    }
}